<?php

namespace api\zhengmaotong\controller;

use api\zhengmaotong\model\AddressModel;
use api\zhengmaotong\model\GoodsModel;
use api\zhengmaotong\model\OrderModel;
use cmf\controller\RestBaseController;
use think\Request;

class OrderController extends RestBaseController
{
    public function order(Request $request)
    {
        $data = $request->post();
        //查询商品
        $goods = GoodsModel::where('id', $data['goods_id'])->find();
        $list = $this->getGoodsInfo($goods, $data['goods_info']);
        if (!$goods) {
            return json(['status' => 'error', 'message' => '商品不存在']);
        }
        if ($goods['status'] != 1) {
            return json(['status' => 'error', 'message' => '商品缺货或者已下架']);
        }
        $address = AddressModel::where('id', $data['address_id'])->find();
        if (!$address) {
            return json(['status' => 'error', 'message' => '地址不存在']);
        }

        $insert_data = [
            'user_id' => $request->userID,
//            'user_id' =>$data['user_id'],
            'goods_name' => $goods['title'],
            'goods_info' => json_encode($data['goods_info']),
            'price' => $list['价格'],
            'num' => $data['num'],
            'total_price' => round($goods['fare'] * $data['num'], 2),
            'trade_no' => date('YmdHis'). mt_rand(1111,9999),
            'user_name' => $address['name'],
            'user_tel' => $address['mobile'],
            'user_address' => $address['area'] . $address['address'],
            'pay_type' => $data['pay_type'],
            'status' => 0,
            'remarks' => $data['remarks'],
            'create_time' => date('Y-m-d H:i:s'),
        ];

        $model = new OrderModel();
        if ($model->save($insert_data)) {
            return json(['status' => 'success', 'message' => '订单创建成功', 'data' => ['order_id' => $model->id]]);
        } else {
            return json(['status' => 'error', 'message' => '订单创建失败']);
        }
    }
//    protected function getGoodsInfo($goods, $spe) {
//        $goodsSpe = json_decode($goods['info'],true);
//        // halt($spe);
//        foreach ($goodsSpe as $val) {
//            if($val['颜色'] == $spe['颜色'] && $val['尺码'] == $spe['尺码'])
//                return $val;
//        }
//    }
    protected function getGoodsInfo()
    {
        $goods_id = input('goods_id/d');
        $goods = GoodsModel::find($goods_id);
        unset($goods['info']);
        $goodsAttr = json_decode($goods['info'],true);
        foreach ($goodsAttr as $key => $val) {
            $goodsAttr[$key]['attr_values'] = explode(',',$val['attr_values']);
        }
        $goods['attr'] = $goodsAttr;
        $this->success('商品详情', $goods);
    }

    protected function getGoodsInfo2($goods, $buy)
    {
        $goodsSku = json_decode($goods['info'], true);
        foreach ($goodsSku as $sku) {
            $hasSku = true;
            foreach ($buy as $attr => $value) {
                if ($sku[$attr] != $value) {
                    $hasSku = false;
                }
            }
            if ($hasSku) {
                return $sku;
            } else {
                continue;
            }
        }
    }
    // CURL
    function curlRequest($type, $url, $contentType, $data = [], $timeout = 60)
    {
        try {
            $type = strtoupper($type);
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url); // 设置请求链接
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 不直接输出页面
            curl_setopt($curl, CURLOPT_HEADER, 0); // 获取响应头向下
            curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);   // 请求超时时间，单位：秒
            curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1');
            if (substr($url, 0, 5) == 'https') {
                // 自动判断是否是 https 提交
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                // https请求，不验证证书和 hosts
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            }
            // 判断 Content-Type 类型
            if ($contentType == 'json') {
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
            }
            if ($contentType == 'form') {
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);
            }
            switch ($type) {
                case "GET" :
                    curl_setopt($curl, CURLOPT_HTTPGET, true);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                    break;
                case "POST":
                    curl_setopt($curl, CURLOPT_POST, true);
                    if ($contentType == 'json') {
                        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                    }
                    if ($contentType == 'form') {
                        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                    }
                    break;
            }
            $result = curl_exec($curl);
            $err_code = curl_errno($curl);
            $curlInfo = curl_getinfo($curl);
            curl_close($curl);
            if ($err_code) {
                return ['status' => 'error', 'msg' => 'sendRequestError:' . $err_code];
            }
            if ($curlInfo['http_code'] == 200) {
                return json_decode($result, true);
            }
            return false;
        } catch (\Exception $e) {
            return ['status' => 'error', 'msg' => $e->getMessage()];
        }
    }

    // 订单物流
    public function wuLiu()
    {
        $url = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";
        // 应用级别参数
        $requestData = [
            'LogisticCode' => '8238783079207',
        ];
        $requestDataJson = json_encode($requestData);

        $apiKey = '16fc7d55-79b7-4e17-9cd7-c54b0059255d';
        $sign = urlencode(base64_encode(md5($requestDataJson . $apiKey)));
        // 其它参数
        $param = [
            'RequestData' => $requestDataJson,
            'RequestType' => 8002,
            'EBusinessID' => 1855255,
            'DataSign' => $sign,
            'DataType' => 2,
        ];
        $res = $this->curlRequest('POST', $url, 'form', $param);

        if ($res) {
            $this->success('查询成功', $res);
        } else {
            $this->error('查询失败');
        }
    }
    }
